<?php
namespace app\sports_admin\controller;
ini_set('memory_limit','1024M');    // 临时设置最大内存占用为1G
set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/29/0029
 * Time: 15:21
 */
use think\Request;
use app\sports_admin\model\Backups as BackupsModel;
use think\Loader;
use app\sports_admin\service\DB as DBService;
Loader::import('backup.Backdb', EXTEND_PATH);
class Backups extends Base
{
    protected $beforeActionList = [
        'isAdmin'=>['only'=>'backups_database,downloadbackupsname'],
        'operationSelect'   =>  ['only'=>'backupslist'],
    ];
    //备份首页
    public function index()
    {
        $dir = './static/data';
        $files = bianli1($dir);
        return view('index',compact('files'));
    }
    /**
     * 获取备份列表
     * @param $page 第几页
     * @param $rows 每页显示的条数
     * @param $sort 要排序的字段
     * @param $sortOrder 升序/降序
     * @param $searchName 要检索的字段
     * @param $start 备份的开始时间
     * @param $end 备份的结束时间
    */
    public function backupsList()
    {
        $params = Request::instance()->only(['page','rows','sort','sortOrder','searchName','start','end']);
        $page = intval($params['page']) ? intval($params['page']) : 1;
        $rows = intval($params['rows']) ? intval($params['rows']) : 15;
        $sort = trim($params['sort']) ? trim($params['sort']) : 'id';
        $sortOrder = trim($params['sortOrder']) ? trim($params['sortOrder']) : 'asc';
        $searchName = trim($params['searchName']);
        $start = trim($params['start']);
        $end = trim($params['end']);
        return BackupsModel::getBackupsList($page,$rows,$sort,$sortOrder,$searchName,$start,$end);
    }
    /**
     * 数据库备份
    */
    public function backups_database()
    {
        //return Request::instance()->url();
       // return 1;
        $db = new DBService(\think\Config::get("database"));
        $info = $db->backup();
        return json(['code'=>200,'msg'=>$info]);
    }
    /**
     * 下载备份文件
     * @param $backupsId 备份id
    */
    public function downloadBackupsName()
    {
        $databaseName = input('get.fileName');
        $path = str_replace("\\","/",ROOT_PATH.'public/static/data/');
        //打开文件
        $fileName = $path.$databaseName.'.sql';
        $file = fopen($fileName, "r");
        //输入文件标签
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . filesize($fileName));
        Header("Content-Disposition: attachment; filename=" . $databaseName.'.sql');
        echo fread($file, filesize($fileName));
        fclose($file);
    }
}